package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.member.domain.UserInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Administrator on 2019/5/30.
 */
public class UserContext {
    private UserContext() {
    }

    //获取session
    public static HttpSession getSession() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest().getSession();
    }
    //将当前用户设置到session作用域中
    public static void addCookie(HttpServletResponse response, String name, String value) {
        Cookie cookie = new Cookie(name,value);
        //设置cookie作用域
        cookie.setPath("/");
        //设置cookie的最大存活时间(单位秒)
        cookie.setMaxAge(1800);
        response.addCookie(cookie);
    }


    //将当前用户设置到session作用域中
    public static void setAttributeUserInfo(UserInfo userInfo) {
        getSession().setAttribute("USERINFO_IN_SESSION", userInfo);
    }

    //将当前用户的权限表达式共享到session作用域
    public static void setAttributeExpressions(List<String> expressions) {
        getSession().setAttribute("EXPRESSIONS_IN_SESSION", expressions);
    }

    //获取当前用户
    public static UserInfo getAttributeUserInfo() {
        return (UserInfo) getSession().getAttribute("USERINFO_IN_SESSION");
    }
    //获取当前用户的权限表达式
    public static List<String> getAttributeExpressions() {
        return (List<String>) getSession().getAttribute("EXPRESSIONS_IN_SESSION");
    }

    public static Cookie getCookie(HttpServletRequest request, String tokenCookie) {
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(tokenCookie)){
                    return cookie;
                }
            }
        }
        return null;
    }
}
